﻿using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraSplashScreen;
using Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using TIMA.DevTeam;

namespace TIMA
{
    public partial class MainForm : RibbonForm
    {
        public int WhoAmI;
        public XForm ActiveXForm = null;

        public MainForm()
        {
            InitializeComponent();
        } 

        #region ShowForm
        public XForm GetActiveForm(Type type, params object[] prm)
        {
            XForm frm;
            string hash = GetHash(type, prm);

            forms.TryGetValue(hash, out frm);

            if (frm != null)
                if (!frm.IsDisposed)
                {
                    frm.Activate();
                    return frm;
                }
                else
                    forms.Remove(hash);

            return null;
        }

        public Dictionary<string, XForm> forms = new Dictionary<string, XForm>();

        private string GetHash(Type type, object[] prm)
        {
            string prmHash = "";
            foreach (object o in prm)
                prmHash += o.GetHashCode();

            return type.GetHashCode() + "." + prmHash;
        }





        public XForm ShowMdiChildForm(Type type, params object[] prm)
        {
            this.Cursor = Cursors.WaitCursor;
            XForm frm = GetActiveForm(type, prm);

            if (frm != null)
            {
                ActiveXForm = frm;
                return frm;
            }

            try
            {
                if (type.BaseType == typeof(XPopupForm))
                {
                    using (XPopupForm popup = (XPopupForm)Activator.CreateInstance(type, prm))
                    {
                        ActiveXForm = popup;
                        frm = popup;
                        popup.ShowDialog();
                    }
                }
                else
                {
                    frm = (XForm)Activator.CreateInstance(type, prm);
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;
                    string hash = GetHash(type, prm);
                    forms.Add(hash, frm);
                    ActiveXForm = frm;
                    frm.Show();

                }
            }
            catch (Exception Ex)
            {
                this.Cursor = Cursors.Default;
                XtraMessageBox.Show(Ex.InnerException.ToString());
            }
            
            this.Cursor = Cursors.Default;
            return frm;
        } 
        #endregion

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F12 && e.Control)
            {
               
            }
        }

        public void SetActiveXFormFromMDIManager()
        {
            if (mdiManager.SelectedPage == null)
                ActiveXForm = null;
            else
            {
                XForm activeForm = mdiManager.SelectedPage.MdiChild as XForm;
                ActiveXForm = activeForm;
            }
        }

        private void mdiManager_SelectedPageChanged(object sender, EventArgs e)
        {
            SetActiveXFormFromMDIManager(); 
        }
          
        public string Info
        {
            set
            {
                string message = value;
                message = message.Replace("\r\n", " ");
                lblInfo.Caption = "[" + DateTime.Now.ToString("HH:mm:ss") + "] " + message;
            }
        }

        BackgroundWorker bwRefresher = new BackgroundWorker();
        public System.Timers.Timer timer;

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.KeyDown += MainForm_KeyDown;

            FormClosing += new FormClosingEventHandler(MainForm_FormClosing);

            ribbon.ToolbarLocation = RibbonQuickAccessToolbarLocation.Hidden;

            //AppSession.MainForm.ShowInTaskbar = false;
            //AppSession.MainForm.WindowState = FormWindowState.Maximized;

            bwRefresher.DoWork += bwRefresher_DoWork;
            bwRefresher.RunWorkerCompleted += bwRefresher_RunWorkerCompleted;

            timer = new System.Timers.Timer(5 * 1000);    //once a minute!
            timer.SynchronizingObject = this;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(RaiseUpdate);
            timer.Enabled = true;

            FabricManager.Init();

            RefreshLocalCopy(FabricManager.GetUpdates());

            InitProducts();

            SplashScreenManager.CloseForm();

            AppSession.MainForm.ShowInTaskbar = true;
            AppSession.MainForm.WindowState = FormWindowState.Maximized;
            //btnProducts.PerformClick();            
        }

        private void InitProducts()
        {
            DataTable dt = FabricManager.ProductsKarbel;
            gv.Init(dt);

            foreach (GridColumn col in gv.Columns)
                col.Visible = false;

            gv.MakeColumnVisibleWithCaptions("ProductId:Fabric Id", "Thumbnail:Scn", "FileName:Origin");
            gv.FocusedRowChanged += gv_FocusedRowChanged;
            //GridMenu gm = GridManager.GetManager(gv).GridMenu;
            //DXMenuItem mi = gm.AddMenu("Find similar fabrics", FindSimilar, false);
            //mi.Image = Properties.Resources.wizard_16x16;

            //mi = gm.AddMenu("Show bigger image", ShowBiggerImage, false);
            //mi.Image = Properties.Resources.zoom_16x16;

            gv.OptionsView.ShowViewCaption = false;
            gv.MakeRowSelectable();
            gv.MakeReadOnly();
            gv.AddSummary();

            gv.BestFitColumns();
        }

        void gv_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            FindSimilar(null, null);
        }

        private void FindSimilar(object sender, EventArgs e)
        {
            int productId = gv.GetFocusedRowCellValue("ProductId").ToIntNN();
            if (productId > 0)
                AppSession.MainForm.ShowMdiChildForm(typeof(Similars), productId);
        }

        private void ShowBiggerImage(object sender, EventArgs e)
        {
            int productId = gv.GetFocusedRowCellValue("ProductId").ToIntNN();
            if (productId > 0)
                AppSession.MainForm.ShowMdiChildForm(typeof(FabricViewer), productId);
        }


        void RaiseUpdate(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer.Enabled = false;            
            RefreshData();
            timer.Enabled = true;
        }

        public void RefreshData()
        {
            if (!bwRefresher.IsBusy)
                bwRefresher.RunWorkerAsync();
        }

        
        void bwRefresher_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                DataTable dtKarbel = (DataTable)e.Result;
                RefreshLocalCopy(dtKarbel);
            }
        }

        private static void RefreshLocalCopy(DataTable dtKarbel)
        {
            if (dtKarbel.Rows.Count > 0)
            {
                foreach (DataRow r in dtKarbel.Rows)
                {
                    int ProductId = (int)r["ProductId"];
                    object localRow = FabricManager.ProductsKarbel.Rows.Find(ProductId);

                    if (localRow != null)
                        FabricManager.ProductsKarbel.Rows.Remove((DataRow)localRow);
                }

                if (dtKarbel.Select("isnull(deleted,0) = 0").Length > 0)
                    FabricManager.ProductsKarbel.Merge(dtKarbel.Select("isnull(deleted,0) = 0").CopyToDataTable());

                FabricManager.RefreshFeatures();
            }
        }

        void bwRefresher_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = FabricManager.GetUpdates();
        }
 

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            FabricManager.Serialize();
        }

      

        private void btnProducts_ItemClick(object sender, ItemClickEventArgs e)
        {
            //ShowMdiChildForm(typeof(Products));
            dock.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
        }

        private void btnUpload_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (FolderBrowserDialog fb = new FolderBrowserDialog())
            {
                if (fb.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    DirectoryInfo di = new DirectoryInfo(fb.SelectedPath);
                    FileInfo[] files = di.GetFiles("*.jpg");
                    if (files.Length > 0)
                    {
                        this.Cursor = Cursors.WaitCursor;
                        foreach (FileInfo fi in files)
                        {
                            Image img = Image.FromFile(fi.FullName);
                            if ((img.Width == 500 && img.Height == 500))
                            {
                                byte[] thumbnail = img
                                                    .CropFromCenter(256)
                                                    .Resize(32)
                                                    .Unsharpen()
                                                    .ToJPEG();

                                byte[] middle = img
                                                    .CropFromCenter(474)
                                                    .Resize(150)
                                                    .Unsharpen()
                                                    .ToJPEG();

                                byte[] bigger = img
                                                    .CropFromCenter(500)
                                                    .Resize(400)
                                                    .Unsharpen()
                                                    .ToJPEG();

                                Data.DM.ExecuteNonQuery("UploadProduct", fi.Name, img.ToJPEG(), thumbnail, middle, bigger);
                            }
                            else
                            {
                                XtraMessageBox.Show("Please upload 500x500 pixel jpgs.");
                                return;
                            }
                        }

                        this.Cursor = Cursors.Default;
                        XtraMessageBox.Show("All done.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    }
                    
                }
            }
        }

        private void ribbon_Click(object sender, EventArgs e)
        {

        }

        private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
        {
            int count = mdiManager.Pages.Count;
            for (int i = 0; i < count; i++)
                mdiManager.Pages[0].MdiChild.Close();

        }

        private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            int count = mdiManager.Pages.Count;
            int i = 0;
            while (count > 1)
            {
                if (mdiManager.Pages[i] != mdiManager.SelectedPage)
                {
                    mdiManager.Pages[i].MdiChild.Close();
                    count--;
                }
                else
                    i++;
            }
        }   
    }
}
